//
//  EmoticionViewController.swift
//  KeyboardDemo
//
//  Created by Lucky on 16/5/13.
//  Copyright © 2016年 Lucky. All rights reserved.
//

import UIKit

private let EmoticonReuseIdentifier = "EmoticonReuseIdentifier"

class EmoticonViewController: UIViewController {
    
    /// 定义一个闭包属性，用于传递选中的表情模型
    var emoticonDidSelectedCallback: (emoticon: Emoticon)->()

    init(callback: (emoticon: Emoticon)->()) {
        self.emoticonDidSelectedCallback = callback
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.redColor()
        
        setupUI()
    }
    
    private func setupUI() {
        view.addSubview(collectionView)
        view.addSubview(toolBar)
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        
        view.addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0.0))
        view.addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0.0))
        view.addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0))
        
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0.0))
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0.0))
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0))
        
        view.addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolBar, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0))
        toolBar.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 44))
        
    }
    
    /// 表情工具条按钮点击
    func itemClick(item: UIBarButtonItem) {
        collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: item.tag), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
    
    // MARK: - 懒加载
    private lazy var collectionView: UICollectionView = {
        let clv = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonLayout())
        clv.backgroundColor = UIColor.whiteColor()
        //注册cell
        clv.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: EmoticonReuseIdentifier)
        clv.dataSource = self
        clv.delegate = self
        return clv
    }()
    
    private lazy var toolBar: UIToolbar = {
        let bar = UIToolbar()
        bar.tintColor = UIColor.darkGrayColor()
        var items = [UIBarButtonItem]()
        
        var index = 0
        
        for package in EmoticonPackage.shareEmoticonPackages() {
            let title = package.group_name_cn
            let item = UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(EmoticonViewController.itemClick(_:)))
            item.tag = index
            index += 1
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        bar.items = items
        return bar
    }()
    
    private lazy var packages: [EmoticonPackage] = EmoticonPackage.shareEmoticonPackages()

}

extension EmoticonViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonReuseIdentifier, forIndexPath: indexPath) as! EmoticonCell
        cell.backgroundColor = UIColor.whiteColor()
        
        let package = packages[indexPath.section]
        
        let emoticon = package.emoticons![indexPath.item]
        
        cell.emoticon = emoticon
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let emoticon = packages[indexPath.section].emoticons![indexPath.item]
        
        emoticon.times += 1
        
        packages[0].appendCurrentEmoticon(emoticon)
        
        emoticonDidSelectedCallback(emoticon: emoticon)
    }
}

/// 自定义cell
class EmoticonCell: UICollectionViewCell {
    
    var emoticon: Emoticon? {
        didSet {
            //1,判断是否是图片表情
            if emoticon?.chs != nil {
                iconButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath!), forState: UIControlState.Normal)
            } else {
                iconButton.setImage(nil, forState: UIControlState.Normal)
            }
            //2,设置emoji表情
            iconButton.setTitle(emoticon?.emojiStr, forState: UIControlState.Normal)
            
            //3,判断是否是删除按钮
            if emoticon!.isRemoveButton {
                iconButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
//                iconButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    private func setupUI() {
        contentView.addSubview(iconButton)
        iconButton.frame = CGRectInset(contentView.bounds, 4, 4)
//        iconButton.layer.borderColor = UIColor.orangeColor().CGColor
//        iconButton.layer.borderWidth = 3
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var iconButton: UIButton = {
        let btn = UIButton()
        
        btn.titleLabel?.font = UIFont.systemFontOfSize(32)
        
        btn.userInteractionEnabled = false
        
        return btn
    }()

}

/// 自定义布局
class EmoticonLayout:UICollectionViewFlowLayout {
    
    override func prepareLayout() {
        super.prepareLayout()
        
        //1，设置cell相关属性
        let width = (collectionView?.bounds.width)! / 7
        itemSize = CGSize(width: width, height: width)
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        //2，设置collectionView相关属性
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
        
        let y = (collectionView!.bounds.height - 3 * width) * 0.48
        collectionView?.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
    }
    
}
